#! /usr/bin/php
<?php
$alphabet = 'QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890';
$path = GetPath();
$argl = array(
	"path" => array(
		"required"	=> 1,
		"hasvalue"	=> 1,
		"desc"		=> "Path to folder with pics",
	),
	"post-set" => array(
		"required"	=> 1,
		"hasvalue"	=> 1,
		"desc"		=> "Name of set",
	),
	"min-size" => array(
		"required"	=> 0,
		"hasvalue"	=> 1,
		"default"	=> 0,
		"desc"		=> "Resize pic to this value if it is smaller than specified.",
	),
	"max-size" => array(
		"required"	=> 0,
		"hasvalue"	=> 1,
		"default"	=> 200,
		"desc"		=> "Resize pic to this value if it is bigger than specified.",
	),
	"jpg-quality" => array(
		"required"	=> 0,
		"hasvalue"	=> 1,
		"default"	=> 60,
		"desc"		=> "JPEG picture quality. Ranges from 0 to 100.",
	),	
);
function GetPath()
{
	global $argv;
	$path = dirname(realpath($argv[0]));
	$ls   = substr($path,-1,1);
	if ($ls != '/' AND $ls != "\\")
		$path.='/';
	return $path;
}
include($path."includes/mod_common.php");
include($path."includes/mod_cli.php");
include($path."includes/mod_images.php");

$procId = GetProcId();
EchoMsg("Start");
ProcessArgs($argl);
if ($args['help'])
	PrintHelp($argl);

if (is_dir($args['path']))
{
	$spath = $args['path'];
}
else
{
	die("Incorrect path specified - $args[path] !");
}
if (!is_dir($path.'/sets/'.$args['post-set']))
{
	mkdir($path.'/sets/'.$args['post-set']);
}
$f = scandir($spath);
foreach($f as $i => $j)
{
	$e1 = explode('.',$j);
	$e = strtolower(end($e1));
	if ($e == 'jpg' OR $e =='jpeg' OR $e == 'gif' OR $e == 'png')
	{
		$im = OpenImage($spath.'/'.$j);
		$w = imagesx($im);
		$h = imagesy($im);		
		if (($w > $args['max-size']) OR ($h > $args['max-size']))
		{
			$w2 = $args['max-size'];
			$h2 = $args['max-size'];
			if ($w < $h)
				$w2 = floor(($args['max-size'] / $h) * $w);
			else
				$h2 = floor(($args['max-size'] / $w) * $h);
		}
		else if (($w < $args['min-size']) OR ($h < $args['min-size']))
		{
			$w2 = $args['min-size'];
			$h2 = $args['min-size'];
			if ($w < $h)
				$w2 = floor(($args['min-size'] / $h) * $w);
			else
				$h2 = floor(($args['min-size'] / $w) * $h);
		}
		if ($w2)
		{
			$im = ImageResize($im,$w2,$h2);
		}
		$r = $path.'/sets/'.$args['post-set']."/".$e1[0]."_".floor(microtime(1)*100).".jpg";
		imagejpeg($im,$r,$args['jpg-quality']);
		imagedestroy ($im);
		EchoMsg("$j was converted into $r");
	}
}



EchoMsg("End.");
?>